/*
 * Copyright (c) 2015. 石头哥哥
 */

package com.suweia.common.suweiredis.serializations;

import org.nustaq.serialization.FSTObjectInput;
import org.nustaq.serialization.FSTObjectOutput;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;


/**
 * 基于fst的序列化方案
 */
public class FstSer implements Serialization {


    /**
     * @return
     */
    public static FstSer getInstance() {
        return Singlton.fstser;
    }


    private FstSer() {
    }

    /**
     * @param obj
     * @return
     */
    @Override
    public byte[] objSerialize(Object obj) {
        ByteArrayOutputStream byteArrayOutputStream = null;
        FSTObjectOutput out = null;
        try {
            // stream closed in the finally
            byteArrayOutputStream = new ByteArrayOutputStream(512);
            out = new FSTObjectOutput(byteArrayOutputStream);  //32000  buffer size
            out.writeObject(obj);
            out.flush();
            return byteArrayOutputStream.toByteArray();
        } catch (IOException ex) {
            ex.printStackTrace();
            return null;
        } finally {
            try {
                if (out != null) {
                    out.close();    //call flush byte buffer
                }
                if (byteArrayOutputStream != null) {
                    byteArrayOutputStream.close();
                }
            } catch (IOException ex) {
                // ignore close exception
            }
        }
    }

    /**
     * @param bytes
     * @return
     */
    @Override
    public Object objDeserialize(byte[] bytes) {
        ByteArrayInputStream byteArrayInputStream = null;
        FSTObjectInput in = null;
        try {
            // stream closed in the finally
            byteArrayInputStream = new ByteArrayInputStream(bytes);
            in = new FSTObjectInput(byteArrayInputStream);
            return in.readObject();
        } catch (Exception ex) {
            ex.printStackTrace();
            return null;
        } finally {
            try {
                if (in != null) {
                    in.close();
                }
                if (byteArrayInputStream != null) {
                    byteArrayInputStream.close();
                }
            } catch (IOException ex) {
                // ignore close exception
            }
        }
    }

    /**
     *
     */
    private static final class Singlton {
        private static final FstSer fstser = new FstSer();
    }
}
